<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>食谱管理 - 健康食谱管理系统</title>
    <link href="https://lib.baomitu.com/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://lib.baomitu.com/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            z-index: 100;
            padding: 48px 0 0;
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
            background-color: #f8f9fa;
            width: 250px;
        }
        .sidebar-sticky {
            position: relative;
            top: 0;
            height: calc(100vh - 48px);
            padding-top: .5rem;
            overflow-x: hidden;
            overflow-y: auto;
        }
        .navbar {
            box-shadow: 0 2px 4px rgba(0,0,0,.1);
        }
        main {
            margin-left: 250px;
            padding: 48px 15px 15px;
        }
        .table-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,.05);
            padding: 1.5rem;
            margin-top: 1rem;
        }
        .nav-link {
            color: #333;
            padding: 0.8rem 1rem;
        }
        .nav-link:hover {
            background-color: #e9ecef;
        }
        .nav-link.active {
            background-color: #007bff;
            color: white;
        }
        .nav-link i {
            width: 20px;
            text-align: center;
            margin-right: 10px;
        }
        .search-box {
            max-width: 300px;
        }
        .recipe-image {
            width: 60px;
            height: 60px;
            border-radius: 8px;
            object-fit: cover;
        }
        .badge {
            font-size: 0.9em;
            padding: 0.4em 0.6em;
        }
        .table td {
            vertical-align: middle;
        }
        .difficulty-badge {
            padding: 0.3em 0.6em;
            border-radius: 4px;
            font-size: 0.85em;
        }
        .difficulty-easy { background-color: #28a745; color: white; }
        .difficulty-medium { background-color: #ffc107; color: black; }
        .difficulty-hard { background-color: #dc3545; color: white; }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-dark bg-dark fixed-top">
        <div class="container-fluid">
            <span class="navbar-brand">健康食谱后台管理</span>
            <div class="d-flex">
                <span class="navbar-text me-3" id="adminName"></span>
                <button class="btn btn-outline-light btn-sm" onclick="handleLogout()">退出</button>
            </div>
        </div>
    </nav>

    <!-- 侧边栏 -->
    <nav class="sidebar">
        <div class="sidebar-sticky">
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link" href="index.html">
                        <i class="fas fa-home"></i>仪表盘
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="users.html">
                        <i class="fas fa-users"></i>用户管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="recipes.html">
                        <i class="fas fa-utensils"></i>食谱管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="foods.html">
                        <i class="fas fa-apple-alt"></i>食材管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="posts.html">
                        <i class="fas fa-comments"></i>帖子管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="sports.html">
                        <i class="fas fa-running"></i>运动记录
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="diets.html">
                        <i class="fas fa-hamburger"></i>饮食记录
                    </a>
                </li>
            </ul>
        </div>
    </nav>

    <!-- 主要内容区域 -->
    <main>
        <div class="container-fluid">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="h2">食谱管理</h1>
                <button class="btn btn-primary" onclick="location.href='recipe-edit.html'">
                    <i class="fas fa-plus"></i> 新增食谱
                </button>
            </div>

            <!-- 搜索框 -->
            <div class="mb-4">
                <div class="input-group search-box">
                    <input type="text" class="form-control" id="searchInput" placeholder="搜索食谱名称...">
                    <button class="btn btn-outline-secondary" type="button" onclick="loadRecipes(1)">
                        <i class="fas fa-search"></i>
                    </button>
                </div>
            </div>

            <!-- 食谱列表 -->
            <div class="table-container">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>图片</th>
                            <th>名称</th>
                            <th>分类</th>
                            <th>烹饪时间</th>
                            <th>难度</th>
                            <th>热量</th>
                            <th>创建者</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="recipeList">
                        <tr>
                            <td colspan="10" class="text-center">加载中...</td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- 分页控件 -->
            <nav aria-label="食谱列表分页" class="mt-4">
                <ul class="pagination justify-content-center" id="pagination"></ul>
            </nav>
        </div>
    </main>

    <!-- 删除确认弹窗 -->
    <div class="modal fade" id="deleteModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    确定要删除这个食谱吗？此操作不可恢复。
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" onclick="handleDelete()">确认删除</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://lib.baomitu.com/twitter-bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentPage = 1;
        let totalPages = 1;
        let deleteId = null;
        const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            showAdminName();
            loadRecipes(1);

            // 搜索框回车事件
            document.getElementById('searchInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    loadRecipes(1);
                }
            });
        });

        // 显示管理员名称
        function showAdminName() {
            try {
                const adminUser = JSON.parse(localStorage.getItem('adminUser') || '{}');
                document.getElementById('adminName').textContent = adminUser.nickname || adminUser.username || '';
            } catch (error) {
                console.error('显示管理员名称失败:', error);
            }
        }

        // 处理退出登录
        function handleLogout() {
            localStorage.removeItem('adminToken');
            localStorage.removeItem('adminUser');
            window.location.href = '/admin/login.html';
        }

        // 加载食谱列表
        async function loadRecipes(page = 1) {
            try {
                const token = localStorage.getItem('adminToken');
                if (!token) {
                    window.location.href = '/admin/login.html';
                    return;
                }

                const search = document.getElementById('searchInput').value;
                const response = await fetch(`/api/admin/recipes?page=${page}&limit=10&search=${search}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (!response.ok) {
                    throw new Error('加载食谱列表失败');
                }

                const result = await response.json();
                if (result.code === 0) {
                    currentPage = page;
                    totalPages = Math.ceil(result.data.total / 10);
                    renderRecipeList(result.data.list);
                    setupPagination();
                }
            } catch (error) {
                console.error('加载食谱列表失败:', error);
                document.getElementById('recipeList').innerHTML = 
                    '<tr><td colspan="10" class="text-center text-danger">加载失败: ' + error.message + '</td></tr>';
            }
        }

        // 渲染食谱列表
        function renderRecipeList(recipes) {
            const tbody = document.getElementById('recipeList');
            if (!recipes || recipes.length === 0) {
                tbody.innerHTML = '<tr><td colspan="10" class="text-center">暂无食谱数据</td></tr>';
                return;
            }

            tbody.innerHTML = recipes.map(recipe => {
                const difficultyClass = getDifficultyClass(recipe.difficulty);
                
                return `
                    <tr>
                        <td>${recipe.id}</td>
                        <td>
                            <img src="${recipe.image || '/images/default-recipe.png'}" 
                                 alt="食谱图片" 
                                 class="recipe-image">
                        </td>
                        <td>${recipe.name}</td>
                        <td>${recipe.category || '-'}</td>
                        <td>${recipe.cookingTime}分钟</td>
                        <td>
                            <span class="difficulty-badge ${difficultyClass}">
                                ${recipe.difficulty}
                            </span>
                        </td>
                        <td>${recipe.nutrition?.calories || '-'}千卡</td>
                        <td>${recipe.creator?.nickname || recipe.creator?.username || '-'}</td>
                        <td>${new Date(recipe.createdAt).toLocaleString()}</td>
                        <td>
                            <button class="btn btn-primary btn-sm me-2" onclick="location.href='recipe-edit.html?id=${recipe.id}'">
                                编辑
                            </button>
                            <button class="btn btn-danger btn-sm" onclick="showDeleteModal(${recipe.id})">
                                删除
                            </button>
                        </td>
                    </tr>
                `;
            }).join('');
        }

        // 设置分页
        function setupPagination() {
            const pagination = document.getElementById('pagination');
            let html = '';

            // 上一页
            html += `
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadRecipes(${currentPage - 1})">上一页</a>
                </li>
            `;

            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (
                    i === 1 || // 第一页
                    i === totalPages || // 最后一页
                    (i >= currentPage - 2 && i <= currentPage + 2) // 当前页附近的页码
                ) {
                    html += `
                        <li class="page-item ${i === currentPage ? 'active' : ''}">
                            <a class="page-link" href="#" onclick="loadRecipes(${i})">${i}</a>
                        </li>
                    `;
                } else if (
                    (i === currentPage - 3 && currentPage > 4) ||
                    (i === currentPage + 3 && currentPage < totalPages - 3)
                ) {
                    html += '<li class="page-item disabled"><span class="page-link">...</span></li>';
                }
            }

            // 下一页
            html += `
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadRecipes(${currentPage + 1})">下一页</a>
                </li>
            `;

            pagination.innerHTML = html;
        }

        // 获取难度对应的样式类
        function getDifficultyClass(difficulty) {
            switch (difficulty) {
                case '简单':
                    return 'difficulty-easy';
                case '中等':
                    return 'difficulty-medium';
                case '困难':
                    return 'difficulty-hard';
                default:
                    return '';
            }
        }

        // 显示删除确认弹窗
        function showDeleteModal(id) {
            deleteId = id;
            deleteModal.show();
        }

        // 处理删除
        async function handleDelete() {
            try {
                const token = localStorage.getItem('adminToken');
                if (!token) {
                    window.location.href = '/admin/login.html';
                    return;
                }

                const response = await fetch(`/api/admin/recipes/${deleteId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (!response.ok) {
                    throw new Error('删除失败');
                }

                const result = await response.json();
                if (result.code === 0) {
                    deleteModal.hide();
                    loadRecipes(currentPage);
                } else {
                    throw new Error(result.message);
                }
            } catch (error) {
                console.error('删除食谱失败:', error);
                alert('删除失败: ' + error.message);
            }
        }
    </script>
</body>
</html>